﻿using System.IO;

namespace Homework19
{
    /// <summary>
    /// 计算C盘中.txt文件的数量
    /// </summary>
    internal class Program
    {
        //定义查找文件路径
        private const string Path = @"C:\";

        //定义文件类型
        private const string SearchPattern = "*.txt";
        static void Main(string[] args)
        {
            //错误防范
            try
            {
                //计算D盘中.txt文件数量
                int countoftxtfiles = CountOfTxtFiles(Path, SearchPattern);

                //输出结果
                Console.WriteLine($"C盘中.txt文件数量为：{countoftxtfiles}");
            }
            catch (Exception ex) 
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            
        }
        static int CountOfTxtFiles(string findpath, string searchPattern) 
        {
            int count = 0;
            try
            {
                // 获取指定路径中所有指定类型文件
                string[] files = Directory.GetFiles(findpath, searchPattern);

                //记录文件数量
                count += files.Length;

                // 获取所有子目录
                string[] directories = Directory.GetDirectories(findpath);

                // 遍历每个子目录
                foreach (string dir in directories)
                {
                    count += CountOfTxtFiles(dir, searchPattern);
                }
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"无法访问目录 {findpath}: {ex.Message}");
            }

            return count;
        }
    }
}
